package com.atguigu.scw.manager.service.impl;

import com.atguigu.scw.manager.bean.TUserRole;
import com.atguigu.scw.manager.bean.TUserRoleExample;
import com.atguigu.scw.manager.dao.TUserRoleMapper;
import com.atguigu.scw.manager.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    private TUserRoleMapper userRoleMapper;

    @Override
    public void addRole(Integer userId, String roleIds) {
        if (roleIds.contains(",")) {
            // 添加多个
            String[] split = roleIds.split(",");
            for (String s : split) {
                // 创建一个中间表的数据对象
                TUserRole userRole = new TUserRole();
                userRole.setUserid(userId);
                userRole.setRoleid(Integer.parseInt(s));
                userRoleMapper.insertSelective(userRole);
            }
        } else {
            TUserRole userRole = new TUserRole();
            userRole.setUserid(userId);
            userRole.setRoleid(Integer.parseInt(roleIds));
            userRoleMapper.insertSelective(userRole);
        }
    }

    @Override
    public void removeRole(Integer userId, String roleIds) {
        if (roleIds.contains(",")) {
            // 删除多个
            String[] split = roleIds.split(",");
            for (String s : split) {
                TUserRoleExample example = new TUserRoleExample();
                TUserRoleExample.Criteria criteria = example.createCriteria();
                criteria.andUseridEqualTo(userId);
                criteria.andRoleidEqualTo(Integer.parseInt(s));
                userRoleMapper.deleteByExample(example);
            }
        } else {
            TUserRoleExample example = new TUserRoleExample();
            TUserRoleExample.Criteria criteria = example.createCriteria();
            criteria.andUseridEqualTo(userId);
            criteria.andRoleidEqualTo(Integer.parseInt(roleIds));
            userRoleMapper.deleteByExample(example);
        }
    }

}